package com.zsguan.z.meixi;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.SimpleAdapter;

import com.zsguan.s.stools4andr.STextTool;
import com.zsguan.s.stools4andr.base.BaseActivity;
import com.zsguan.z.slogger4andr.ZLogger;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class MainActivity extends BaseActivity implements AdapterView.OnItemClickListener {

    private static final String KEY = "path";
    public static final String TITLE = "title";
    public static final String INTENT = "intent";

    private GridView main_grid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        main_grid = (GridView) findViewById(R.id.main_grid);

        setup();
    }

    private void setup() {
        String path = getIntent().getStringExtra(KEY);

        main_grid.setAdapter(new SimpleAdapter(this, getData(path),
                R.layout.item_main_grid, new String[]{TITLE},
                new int[]{R.id.item_name}));
        main_grid.setOnItemClickListener(MainActivity.this);
    }

    protected List<? extends Map<String, ?>> getData(String prefix) {
        List<Map<String, ?>> myData = new ArrayList<>();

        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(getPackageName());

        PackageManager pm = getPackageManager();
        List<ResolveInfo> list = pm.queryIntentActivities(mainIntent, 0);

        if (null == list)
            return myData;

        String[] prefixPath;

        if (STextTool.isEmpty(prefix)) {
            prefix = "";
            prefixPath = null;
        } else {
            prefixPath = prefix.split("/");
        }

        int len = list.size();

        Map<String, Boolean> entries = new HashMap<>();

        for (int i = 0; i < len; i++) {
            ResolveInfo info = list.get(i);
            CharSequence labelSeq = info.loadLabel(pm);
            String label = labelSeq != null ? labelSeq.toString()
                    : info.activityInfo.name;

            if (prefix.length() == 0 || label.startsWith(prefix)) {

                String[] labelPath = label.split("/");

                String nextLabel = prefixPath == null ? labelPath[0]
                        : labelPath[prefixPath.length];

                if ((prefixPath != null ? prefixPath.length : 0) == labelPath.length - 1) {
                    addItem(myData, nextLabel, activityIntent(
                            info.activityInfo.applicationInfo.packageName,
                            info.activityInfo.name));
                } else {
                    if (entries.get(nextLabel) == null) {
                        addItem(myData, nextLabel, browseIntent(prefix
                                .equals("") ? nextLabel : prefix + "/"
                                + nextLabel));
                        entries.put(nextLabel, true);
                    }
                }
            }
        }

        Collections.sort(myData, sDisplayNameComparator);

        return myData;
    }

    private final static Comparator<Map> sDisplayNameComparator = new Comparator<Map>() {
        private final Collator collator = Collator.getInstance();

        public int compare(Map map1, Map map2) {
            return collator.compare(map1.get(TITLE), map2.get(TITLE));
        }
    };

    protected Intent activityIntent(String pkg, String componentName) {
        Intent result = new Intent();
        result.setClassName(pkg, componentName);
        return result;
    }

    protected Intent browseIntent(String path) {
        Intent result = new Intent();
        result.setClass(this, MainActivity.class);
        result.putExtra(KEY, path);
        return result;
    }

    protected void addItem(List<Map<String, ?>> data, String name, Intent intent) {
        Map<String, Object> temp = new HashMap<>();
        temp.put(TITLE, name);
        temp.put(INTENT, intent);
        data.add(temp);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_settings) {
            ZLogger.i(item.toString());
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Map map = (Map) parent.getItemAtPosition(position);

        Intent intent = (Intent) map.get(INTENT);
        ZLogger.i(intent.getComponent().toShortString());

        startActivity(intent);
    }
}
